<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\StudentCourseModel;
use Illuminate\Http\Request;
use App\Models\StudentSignModel;

class StudentCourseController extends Controller
{
    public function page(Request $request) {

        $query = StudentCourseModel::where('company_id', $request->company_id);
        if ($request->student_id > 0) {
            $query->where('student_id', $request->student_id);
        }
        if ($request->course_id > 0) {
            $query->where('course_id', $request->course_id);
        }
        if ($request->pay_status < 2) {
            $query->where('pay_status', $request->pay_status);
        }
        if ($request->begin_date) {
            $query->where('created_at', '>=', $request->begin_date);
        }
        if ($request->end_date) {
            $query->where('created_at', '<=', $request->end_date);
        }

        
       $studentCourses = $query->orderBy('id', 'desc')->paginate($request->per_page, ['*'], 'page', $request->page);
       return self::ok($studentCourses);
    }

    public function save(Request $request) {
        $id = $request->id;
        $studentCourse = $id > 0 ? StudentCourseModel::find($id) : new StudentCourseModel();
        $studentCourse->fill($request->all());
        $studentCourse->send_num = $studentCourse->send_num ?: 0;
        $studentCourse->learned_num = $studentCourse->learned_num ?: 0;
        $studentCourse->valid_end_date = self::calculateCourseEndDate($studentCourse->valid_begin_date, $studentCourse->valid_time_len);
        $studentCourse->save();
        return self::ok($studentCourse);
    }
    /*计算课程结束日期*/ 
    private static function calculateCourseEndDate($validBeginDate, $validMonth) {
        if (!$validBeginDate)  {
            return null;
        }
        if (!$validMonth) {
            return date('Y-m-d', strtotime("+10 year", strtotime($validBeginDate)));
        }

        $validBeginDate = strtotime($validBeginDate);
        $validEndDate = date('Y-m-d', strtotime("+{$validMonth} month", $validBeginDate));
        return $validEndDate;
    }

    public function delete(Request $request) {
        $studentCourse = StudentCourseModel::find($request->id);
        if ($studentCourse) {
            $studentCourse->delete();
            return self::ok();
        }
    }

    public function signs(Request $request) {
        $signs = StudentSignModel::courseSigns($request->studentId, $request->courseId);
        return self::ok($signs);
    }
}
